package com.aierkeji.call.b2c.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aierkeji.call.b2c.dao.jpa.AkjCallClueStatisticsDao;
import com.aierkeji.call.b2c.entity.AkjCallClueStatistics;
import com.aierkeji.call.b2c.entity.AkjCallClueStatisticsVo;
import com.aierkeji.call.b2c.entity.AkjCallUser;
import com.aierkeji.call.b2c.queue.StatisticsQueue;
import com.aierkeji.call.b2c.util.AppConfig;
import com.aierkeji.call.b2c.util.DateTimeUtils;
import com.aierkeji.call.b2c.util.ResultMapHelper;
import com.aierkeji.call.b2c.util.StringUtils;

@Service
public class AkjCallClueStatisticsService {
	private final Logger log = LogManager.getLogger(getClass());

	@Autowired
	private AkjCallClueStatisticsDao akjCallClueStatisticsDao;

//	public Map<String, Object> updateStatistics(Map<String, Object> map) {
//		
//		try {
//			String userId = (String)map.get("userId");
//			
//			List<AkjCallClueStatistics> statisticsList = null;
//			
//			LocalDate localDate = LocalDate.now();
//			
//			int year = localDate.getYear();
//			int month = localDate.getMonthValue();
//			int day = localDate.getDayOfMonth();
//	//		ZoneId zone = ZoneId.systemDefault();
//	//	    Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
//	//	    Date nowDate = Date.from(instant);
//		    
//		    if(StringUtils.isNotEmpty(userId)) {
//		    	statisticsList = akjCallClueStatisticsDao.findByYearAndMonthAndDayAndCallUserId((long)year,(long)month,(long)day,Long.valueOf(userId));
//			}else {
//				statisticsList = akjCallClueStatisticsDao.findByYearAndMonthAndDay((long)year,(long)month,(long)day);
//			}
//		    
//			
//			for(AkjCallClueStatistics statistics : statisticsList){
//				
//				AkjCallClueStatistics result = akjCallClueStatisticsDao.getStatisticsByProcedure(statistics.getCallUserId(),statistics.getGroupId(),statistics.getCreatedAt());
//				result = (AkjCallClueStatistics)BeanUtil.combineSydwCore(result, statistics);
//				akjCallClueStatisticsDao.save(result);
//			}
//		}catch (Exception e) {
//			e.printStackTrace();
//			return ResultMapHelper.failure("更新统计数据时出错了!");
//		}
//		return ResultMapHelper.success();
//	}
	@Transactional(rollbackOn=Exception.class)
	public Map<String, Object> updateStatistics(Map<String, Object> map) throws Exception {

		try {
			String leaderId 		= (String) map.get("leaderId");
			String speciallyTime 	= (String) map.get("speciallyTime");
			String userId 			= (String) map.get("userId");

			if(StringUtils.isEmpty(userId)) {
				if (ThreadContext.getSubject() != null) {
					AkjCallUser akjCallUser = (AkjCallUser) SecurityUtils.getSubject().getSession()
							.getAttribute("loginUser");
					if (akjCallUser != null) {
						leaderId = String.valueOf(akjCallUser.getId());
					}
				}
			}
			

			Date initDate 	= DateTimeUtils.getTodayStart();
			Date finshDate 	= DateTimeUtils.getEndTime();

			if (StringUtils.isNotEmpty(speciallyTime)) {
				initDate 	= DateTimeUtils.getDayBefore(DateTimeUtils.getTodayStart());
				finshDate 	= DateTimeUtils.getDayBefore(DateTimeUtils.getEndTime());
			}

			String initTodayStr = DateTimeUtils.converDateToString(initDate, DateTimeUtils.DATE_PATTERN_TIMESTAMP);
			String finish 		= DateTimeUtils.converDateToString(finshDate, DateTimeUtils.DATE_PATTERN_TIMESTAMP);
			
			log.info("callStatisticsProcedure params ,leaderId:{}---initTodayStr:{}---finish:{}---speciallyTime:{}----userId:{}",leaderId, initTodayStr, finish, speciallyTime,userId);
			
			akjCallClueStatisticsDao.callStatisticsProcedure(leaderId, userId, initTodayStr, finish, speciallyTime);
			
		} catch (Exception e) {
			log.error("",e);
			throw new Exception(" error call updateStatistics rollback",e);
		}
		return ResultMapHelper.success("更新统计数据成功！");
	}

	public Map<String, Object> getUserStatistics(Map<String, Object> map) {
		AkjCallClueStatisticsVo statistics = null;
		
		String intervalTime = AppConfig.getProperty("statisticsIntervalTime", "");
		
		String startTime = (String) map.get("startTime");
		
		String toDay = DateTimeUtils.converDateToString(DateTimeUtils.getCurrentTime(),DateTimeUtils.DATE_PATTERN_DAY);
		
		if (StringUtils.isEmpty(startTime)) {
			startTime = toDay;
		}
		
		AkjCallUser akjCallUser = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
		
		Map<String, Object> resultMap 			= new HashMap<String, Object>();
		Map<String, Object> updateStatisticsMap = new HashMap<String, Object>();
		updateStatisticsMap.put("userId", akjCallUser.getId().toString());
		
		String initTodayStr = startTime + " 00:00:00";
		String finish = startTime + " 23:59:59";
		
		try{
		
			if(!startTime.equals(toDay)){
				log.info("-------不等于今天进入方法-------"+akjCallUser.getId(),initTodayStr, finish);
				statistics = akjCallClueStatisticsDao.getUserStatistics(akjCallUser.getId(),initTodayStr, finish);
				
			}else{
				
				String[] arr = startTime.split("-");
				List<AkjCallClueStatistics> listClueStatistics = akjCallClueStatisticsDao.findByYearAndMonthAndDayAndCallUserId(Long.valueOf(arr[0]), Long.valueOf(arr[1]), Long.valueOf(arr[2]),akjCallUser.getId());
				
				if(listClueStatistics.size()>0){
					
					AkjCallClueStatistics clueStatistics = listClueStatistics.get(0);
					
					Date statisticsDate = clueStatistics.getStatisticsCreatedAt();
					Long statisticsTime = statisticsDate.getTime()+(Integer.valueOf(intervalTime)*60*1000);
					
					Date date = DateTimeUtils.getCurrentTime();
					Long fiveMin = date.getTime();
					//是否5分钟内
					if(statisticsTime > fiveMin){
						log.info("-------5分钟内进入方法-------"+akjCallUser.getId(),initTodayStr, finish);
						statistics = akjCallClueStatisticsDao.getUserStatistics(akjCallUser.getId(),initTodayStr, finish);
					}else{
						log.info("-------超过了5分钟内进入方法并且重新统计数据-------"+akjCallUser.getId(),initTodayStr, finish);
						resultMap = this.updateStatistics(updateStatisticsMap);
						statistics = akjCallClueStatisticsDao.getUserStatistics(akjCallUser.getId(),initTodayStr, finish);
					}
					
				}else{
					log.info("-------无统计数据进入方法-------"+akjCallUser.getId(),initTodayStr, finish);
					resultMap = this.updateStatistics(updateStatisticsMap);
					statistics = akjCallClueStatisticsDao.getUserStatistics(akjCallUser.getId(),initTodayStr, finish);
				}
			}
		
		}catch(Exception e){
			log.error("AkjCallClueStatisticsService.getUserStatistics is fault", e,map);
			return ResultMapHelper.failure("系统出错拉，查询失败");
		}
		log.info("-------总共有"+statistics.getClueTotal()+"条数据------");
		
		if (statistics == null) {
			return ResultMapHelper.failure("暂无数据");
		}

		return ResultMapHelper.success(statistics);
	}

	public Map<String, Object> getStatisticsByAssigneUser(Map<String, Object> map) {
		String assigneTime = (String) map.get("assigneTime");
		String assigneUserId = (String) map.get("assigneTo");

		AkjCallUser akjCallUser = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");

		if (StringUtils.isEmpty(assigneTime)) {
			assigneTime = DateTimeUtils.converDateToString(DateTimeUtils.getCurrentTime(),
					DateTimeUtils.DATE_PATTERN_DAY);
		}

		String initDate = assigneTime + " 00:00:00";
		String finishDate = assigneTime + " 23:59:59";

		AkjCallClueStatisticsVo statistics = akjCallClueStatisticsDao.getStatisticsByAssigneUser(assigneUserId,
				akjCallUser.getId(), initDate, finishDate);
		if (statistics == null) {
			return ResultMapHelper.failure("暂无数据");
		}

		return ResultMapHelper.success(statistics);
	}

	public Map<String, Object> putStaticsQueue(Map<String, Object> map) {
		// TODO Auto-generated method stub

		AkjCallUser akjCallUser = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
		if (akjCallUser != null) {
			String leaderId = String.valueOf(akjCallUser.getId());
			map.put("leaderId", leaderId);
		}
		try {
			StatisticsQueue.linkedBlockingQueue.add(map);
		} catch (Exception e) {
			// TODO: handle exception
			log.error("StatisticsQueue.linkedBlockingQueue is full", e);
			return ResultMapHelper.failure("请求更新次数太频繁，请稍后再试。");
		}

		return ResultMapHelper.success("成功提交更新统计数据申请，请稍等！");
	}
}
